<?php

/*
	info: 用户注册
	date: 2011-12-20
*/

define('PAGESCRIPT', 'register');
define('USER_LOGIN_CHECK', TRUE);
require dirname(__FILE__).'/include/common.inc.php';
global_ConnectDB();
$webglobal['file_register'] = array();

if ($user['base_uid'] > 0)
{
	$tempgourl = (!empty($webserver['comeurl']) && !preg_match('/^.*login.*$/', $webserver['comeurl'])) ? $webserver['comeurl'] : WEBURLPATH.'/index.php';
	global_ShowMessage("欢迎回来，{$user['base_username']}。", $tempgourl);
}

//用户激活
if ($webglobal['action']=='active')
{
	global_CheckPost(
			array(
				array('code','str','','',0,''),
		));
	$temparray = explode(',', global_DecryptKey($webglobal['CPP']['code'], WEBAUTHKEY));
	if (count($temparray) != 3)
	{
		global_ShowMessage("参数错误。");
	}
	$tempuserinfo = $db->GetOne("SELECT * FROM {$webconfig['dbpre']}user WHERE id='".intval($temparray[0])."'");
	if (!empty($tempuserinfo) && $tempuserinfo['status']==-1 && $tempuserinfo['authcode']==$temparray[1])
	{
		$db->Update('user', array('authcode'=>'','status'=>0,'loginip'=>$user['ip'],'logintime'=>$webserver['timestamp']), "id='{$tempuserinfo['id']}'");
		$usercheckobj->SetUserCookie($tempuserinfo['id'], $tempuserinfo['pwd'], 0);
		global_ShowMessage("{$tempuserinfo['nickname']}，恭喜您，已经成功激活帐号。", WEBURLPATH.'/index.php');
	}
	else
	{
		global_ShowMessage("参数错误。");
	}
}
//商家注册
elseif ($webglobal['action']=='regcom')
{
	$webglobal['file_register']['category'] = $companyCategoryDataModel->formatCategoryOption(0,0);
	$webglobal['file_register']['area_json'] = $areaDataModel->formatClassToJson(0, 0);
	$webglobal['file_register']['area_tree'] = '';
	$webglobal['file_register']['imagepath'] = '/upfiles/company/'.global_FormatTime(0, 'Ym');
	$webglobal['file_register']['logosetting'] = $webglobal['file_register']['bcodesetting'] = array('type'=>array('gif', 'jpg', 'jpeg', 'png', 'bmp'), 'size'=>2097152);

	if (isset($webrequest['check']))
	{
		include_once WEBFILEPATH.'/include/upload.class.php';
		global_CheckPost(
				array(
					array('company_category_id,','int','isset($webglobal[\'file_register\'][\'category\'][@])','请选择商家分类',1),
					array('username,','username','','用户名只能为字母开头的数字字母组合，4-15位长度',1),
					array('email,','email','','email格式不合法',1),
					array('password','password','','密码至少为6位',1),
					array('passwordtwo','password','','重复密码至少为6位',1),
					array('name,','str','','商家名称不能空',1),
					array('english_name,','str','','商家别名不能空',1),
					array('bcode,','str','','营业执照代码不能为空',1),
					array('area_id,','int','','请选择对应的商圈',1),
					array('address,','str','','商家地址不能为空',1),
					array('tel,','str','','电话不能为空',1),
					array('site,','url','','',0,''),
					array('latitude,','','preg_match("/^[0-9]+\.[0-9]+$/", @)','',0,0),
					array('longitude,','','preg_match("/^[0-9]+\.[0-9]+$/", @)','',0,0),
					array('description,','str','','商家介绍不能为空',1),
			));
		//其他要求判断
		if (empty($webglobal['CPM']))
		{
			echo $webglobal['CPP']['english_name'];
			if ($webglobal['CPP']['password']!=$webglobal['CPP']['passwordtwo'])
			{
				$webglobal['CPM']['passwordtwo'] = '两次输入的密码不一样';
			}
			if ($webglobal['CPP']['name']=='' || $webglobal['CPP']['english_name']=='')
			{
				$webglobal['CPM']['name'] = '商家中文名称和英文名称必填一个';
			}
			if (!isset($webglobal['areadata'][$webglobal['CPP']['area_id']]))
			{
				$webglobal['CPM']['area_id'] = '系统中不存在该商圈';
			}
			elseif ($webglobal['areadata'][$webglobal['CPP']['area_id']]['level'] != 3)
			{
				$webglobal['CPM']['area_id'] = '所选择的商圈不合法';
			}
			else
			{
				$parentArea = $webglobal['areadata'][$webglobal['CPP']['area_id']]['upCategoryID'];
				foreach ($parentArea as $areaId)
				{
					if (isset($webglobal['areadata'][$areaId]))
					{
						switch ($webglobal['areadata'][$areaId]['level'])
						{
							case 0:
								$webglobal['CPD']['province'] = $areaId;
								break;
							case 1:
								$webglobal['CPD']['city'] = $areaId;
								break;
							case 2:
								$webglobal['CPD']['district'] = $areaId;
								break;
						}
					}
				}
			}
			$checkarray = array();
			if (!empty($webglobal['CPP']['username']))
			{
				$checkarray[] = "username='{$webglobal['CPP']['username']}'";
			}
			if (!empty($webglobal['CPP']['email']))
			{
				$checkarray[] = "email='{$webglobal['CPP']['email']}'";
			}
			if (!empty($webglobal['CPP']['name']))
			{
				$checkarray[] = "name='{$webglobal['CPP']['name']}'";
			}
			if (!empty($webglobal['CPP']['english_name']))
			{
				$checkarray[] = "english_name='{$webglobal['CPP']['english_name']}'";
			}
			if (!empty($webglobal['CPP']['bcode']))
			{
				$checkarray[] = "bcode='{$webglobal['CPP']['bcode']}'";
			}
			if (!empty($checkarray))
			{
				$query = $db->Query("SELECT * FROM {$webconfig['dbpre']}company WHERE ".implode(' OR ', $checkarray));
				while ($tempdata = $db->FetchArray($query))
				{
					if (!empty($webglobal['CPP']['username']) && $tempdata['username']==$webglobal['CPP']['username'])
					{
						$webglobal['CPM']['username'] = '用户名数据库中已存在';
					}
					if (!empty($webglobal['CPP']['email']) && $tempdata['email']==$webglobal['CPP']['email'])
					{
						$webglobal['CPM']['email'] = 'E-mail数据库中已存在';
					}
					if (!empty($webglobal['CPP']['name']) && $tempdata['name']==$webglobal['CPP']['name'])
					{
						$webglobal['CPM']['name'] = '商家名称数据库已存在';
					}
					if (!empty($webglobal['CPP']['english_name']) && $tempdata['english_name']==$webglobal['CPP']['english_name'])
					{
						$webglobal['CPM']['english_name'] = '商家别名数据库中已存在';
					}
					if (!empty($webglobal['CPP']['bcode']) && $tempdata['bcode']==$webglobal['CPP']['bcode'])
					{
						$webglobal['CPM']['bcode'] = '营业执照代码数据库中已存在';
					}
				}
			}
		}
		//上传判断
		if (empty($webglobal['CPM']))
		{
			$templogoupload = new Upload('logo', $webglobal['file_register']['logosetting']);
			if (!$templogoupload->CheckFile() && !$templogoupload->isNone)
			{
				$webglobal['CPM']['logo'] = 'logo图片: '.$templogoupload->errorMsg;
			}
			$tempbcodeupload = new Upload('bcode_image', $webglobal['file_register']['bcodesetting']);
			if (!$tempbcodeupload->CheckFile())
			{
				$webglobal['CPM']['bcode_image'] = '营业执照图片: '.$tempbcodeupload->errorMsg;
			}
		}
		//检查完毕保存
		if (empty($webglobal['CPM']))
		{
			$webglobal['CPD']['pwd'] = global_Md5($webglobal['CPP']['password']);
			$webglobal['CPD']['description'] = global_ConvNewline($webglobal['CPD']['description']);
			if ($templogoupload->CheckFile())
			{
				$templogoupload->SaveFile(WEBFILEPATH.$webglobal['file_register']['imagepath']);
				$webglobal['CPD']['logo'] = $webglobal['file_register']['imagepath'].'/'.$templogoupload->fileList[0]['name'];
			}
			if ($tempbcodeupload->CheckFile())
			{
				$tempbcodeupload->SaveFile(WEBFILEPATH.$webglobal['file_register']['imagepath']);
				$webglobal['CPD']['bcode_image'] = $webglobal['file_register']['imagepath'].'/'.$tempbcodeupload->fileList[0]['name'];
			}
			$webglobal['CPD']['status'] = 0;
			$webglobal['CPD']['addtime'] = $webserver['timestamp'];
			$tempadduid = $db->Insert('company', '', TRUE);
			global_ShowMessage("恭喜您！注册成功。商家注册后需要审核，审核通过后我们会在三个工作日内联系您，谢谢！");
		}
		//商圈默认值
		if (isset($webglobal['CPP']['area_id']) && isset($webglobal['areadata'][$webglobal['CPP']['area_id']]))
		{
			$parentArea = $webglobal['areadata'][$webglobal['CPP']['area_id']]['upCategoryID'];
			array_shift($parentArea);
			$webglobal['file_register']['area_tree'] = implode(',', $parentArea) . ',' .$webglobal['CPP']['area_id'];
		}
	}
}
//个人注册
else
{
	$webglobal['err_message'] = array();
	if (isset($webrequest['check']))
	{
		global_CheckPost(
			array(
				array('email','email','','E-mail地址格式错误',1),
				//array('username','username','','用户名格式错误',1),
				array('nickname','nickname','','昵称不能为空',1),
				array('password','password','','密码至少为6位',1),
				array('passwordtwo','password','','重复密码至少为6位',1),
		));
		if (empty($webglobal['CPM']))
		{
			if ($webglobal['CPP']['password']!=$webglobal['CPP']['passwordtwo'])
			{
				$webglobal['CPM']['passwordtwo'] = '两次输入的密码不一样';
			}

			if (strlen($webglobal['CPP']['nickname']) > 20) {
				$webglobal['CPM']['nickname'] = '昵称输入超出范围';
			}

			/*
			$temphaveuser = $db->GetNum("SELECT COUNT(*) FROM {$webconfig['dbpre']}user WHERE nickname='{$webglobal['CPP']['nickname']}'");
			if ($temphaveuser > 0) {
				$webglobal['CPM']['username'] = '您注册的昵称已经存在,请重新换一个昵称';
			}
			*/
			$temphaveemail = $db->GetNum("SELECT COUNT(*) FROM {$webconfig['dbpre']}user WHERE email='{$webglobal['CPP']['email']}'");
			if ($temphaveemail > 0)
			{
				$webglobal['CPM']['email'] = '您注册的E-mail地址已经存在';
			}
		}
		if (!empty($webglobal['CPM']))
		{
			$webglobal['err_message'] = $webglobal['CPM'];
		}
		else
		{
			$temprandnum = global_Random(6);
			$tempadduid = $db->Insert('user', array(
								'nickname' => $webglobal['CPP']['nickname'],
								'email' => $webglobal['CPP']['email'],
								'username' => $webglobal['CPP']['email'],
								'pwd' => global_Md5($webglobal['CPP']['password']),
								'authcode' => $temprandnum,
								'status' => -1,
								'score' => isset($webcache['setting']['extcredits']['user_register']) ? $webcache['setting']['extcredits']['user_register'] : 0,
								'regip' => $user['ip'],
								'regtime' => $webserver['timestamp'],
							), TRUE);
			$tempactiveurl = "http://{$webserver['webhost']}".WEBURLPATH."/register.php?action=active&code=".global_EncryptKey("{$tempadduid},{$temprandnum},{$webserver['timestamp']}", WEBAUTHKEY);
			include_once WEBFILEPATH.'/include/email.class.php';
			$sendemailobj = new Email();
			$sendemailobj->Send($webglobal['CPP']['email'], "{$webcache['setting']['sitename']} 用户注册激活邮件", "亲爱的{$webglobal['CPP']['nickname']}：<br />&nbsp;&nbsp;&nbsp;&nbsp;感谢您注册，点击以下链接马上激活帐号，如果不能点击请复制以下链接到浏览器地址栏打开。<br /><a href=\"{$tempactiveurl}\" target=\"_blank\">$tempactiveurl</a>", 1);
			
			$redirectUrl = getEmailResource($webglobal['CPP']['email']);
			global_ShowMessage("恭喜您！注册成功。请查看邮箱邮件完成帐号激活。", $redirectUrl);
		}
	}
}

function getEmailResource($email = '') {
	$standarEmailAddress = array(
		'163'     => 'http://mail.163.com/',
		'126'     => 'http://mail.126.com/',
		'sina'    => 'http://mail.sina.com.cn/',
		'yahoo'   => 'http://mail.cn.yahoo.com/',
		'sohu'    => 'http://mail.sohu.com/',
		'yeah'    => 'http://www.yeah.net/',
		'gmail'   => 'http://gmail.google.com/',
		'hotmail' => 'http://www.hotmail.com/',
		'live'    => 'http://www.hotmail.com/',
		'qq'      => 'https://mail.qq.com/',
		'139'     => 'http://mail.10086.cn/'
	);

	$mailAddress = '';
	if (preg_match("/^[\w\-\.]+@([\w\-\.]+)(\.\w+)+$/", $email, $matches)) {
		if (isset($matches[1]) && $matches[1]) {
			foreach ($standarEmailAddress as $key => $email) {
				if (strpos($matches[1], $key) !== false) {
					$mailAddress = $email;
					break;
				}
			}

			if ($mailAddress == '') {
				$mailAddress = 'http://mail.' . $matches[1] . $matches[2];
			}
		}
	}
	
	return $mailAddress;
}

template_Display('register');
